package lt.inkredibl.iit.action;

import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.event.ActionEvent;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.Spring;
import javax.swing.SpringLayout;
import javax.swing.SpringLayout.Constraints;

import lt.inkredibl.swing.AbstractAction;

public class DimensionsFrame
	extends JDialog
{
	private JTextField _width;
	private JTextField _height;
	private Dimension _ret;

	public DimensionsFrame(JFrame owner, String title, int width, int height)
	{
		super(owner, title, true);
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
		setLocationRelativeTo(owner);
		Container cp = getContentPane();
		SpringLayout layout = new SpringLayout();
		cp.setLayout(layout);
		_width = new JTextField(String.valueOf(width));
		_height = new JTextField(String.valueOf(height));
		SpringUtils su = new SpringUtils();
		Component[][] comps = {
			{new JLabel("Width:"), new JLabel(""), new JLabel("Height:")},
			{_width, new JLabel("x"), _height},
		};
		Spring space = Spring.constant(5);
		su.setComps(cp, comps, space, space);
		Constraints c = layout.getConstraints(cp);
		Spring w = c.getWidth();
		Spring h = c.getHeight();
		JButton ok = new JButton(new AbstractAction() {
			{
				setName("OK");
			}
			public void actionPerformed(ActionEvent e)
			{
				_ret = new Dimension(Integer.parseInt(_width.getText()), Integer.parseInt(_height.getText()));
				dispose();
			}
		});
		JButton cancel = new JButton(new AbstractAction() {
			{
				setName("Cancel");
			}
			public void actionPerformed(ActionEvent e)
			{
				_ret = null;
				dispose();
			}
		});
		cp.add(ok);
		cp.add(cancel);
		Constraints cok = layout.getConstraints(ok);
		Constraints ccancel = layout.getConstraints(cancel);
		cok.setY(h);
		ccancel.setY(h);
		h = su.sum(su.max(cok.getConstraint(SpringLayout.SOUTH), ccancel.getConstraint(SpringLayout.SOUTH)), space);
		Spring left = Spring.constant(5, 5, Integer.MAX_VALUE);
		cok.setX(left);
		ccancel.setX(su.sum(cok.getConstraint(SpringLayout.EAST), space));
		w = su.max(w, su.sum(ccancel.getConstraint(SpringLayout.EAST), space));
		c.setWidth(w);
		c.setHeight(h);
	}

	public DimensionsFrame(JFrame owner, String string, double width, double height)
	{
		this(owner, string, (int)width, (int)height);
	}

	public Dimension chooseDimensions()
	{
		pack();
		setVisible(true);
		return _ret;
	}
}
